﻿using CommunityToolkit.Mvvm.ComponentModel;
using Company.Core.Helper;
using Company.Hardware.Ice_ipc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Company.Hardware
{
    public class CameraIce : ObservableObject, ICameraIce
    {
        private Task _task;
        private bool _initialized;
        private bool _connected;
        private string _message;
        private string _value;
        private IntPtr intPtr;

        public bool Initialized { get => _initialized; set => SetProperty(ref _initialized, value); }
        public bool Connected { get => _connected; set => SetProperty(ref _connected, value); }
        public string Message { get => _message; set => SetProperty(ref _message, value); }
        public string Value { get => _value; set => SetProperty(ref _value, value); }

        public event Action<string> MessageChanged;
        public event Action<string> ValueChanged;

        public void Close()
        {
            intPtr = IntPtr.Zero;
            ipcsdk.ICE_IPCSDK_Close(intPtr);
            ipcsdk.ICE_IPCSDK_Fini();
        }

        public void Open()
        {
            throw new NotImplementedException();
        }

        public bool OpenPreview(string pcIP, byte u8OverTCP, byte u8MainStream, uint hWnd, ipcsdk.ICE_IPCSDK_OnPlate pfOnPlate, IntPtr pvPlateParam)
        {
            intPtr = ipcsdk.ICE_IPCSDK_OpenPreview(pcIP, 0, 0, hWnd, pfOnPlate, new IntPtr(0));
            if(intPtr == IntPtr.Zero)
            {
                MessageChanged?.Invoke("ICE摄像头连接失败");
                return false;
            }
            MessageChanged?.Invoke($"ICE摄像头连接成功");
            Initialized = true;
            Connected = true;
            return true;
        }
        /// <summary>
        /// 车牌识别
        /// </summary>
        /// <param name="carName"></param>
        
        public void Trigger(string carName)
        {
            if (!_connected)
            {
                MessageChanged?.Invoke("ICE摄像头连接失败");
                return;
            }
            try
            {
                StringBuilder strNum = new StringBuilder(32);
                StringBuilder strColor = new StringBuilder(64);
                uint len = 0;
                //IntPtr pLen = Marshal.AllocHGlobal(32);
                byte[] pdata = new byte[1048576];
                uint success = 0;
                if (_task == null)
                {
                    _task = Task.Factory.StartNew(() =>
                    {
                        while (intPtr!= IntPtr.Zero)
                        {
                            Task.Delay(50).Wait();

                            /**
                             *  @brief  软触发
                             *  @param  [IN]  hSDK          由连接相机接口获得的句柄
                             *  @param  [OUT] pcNumber      车牌号
                             *  @param  [OUT] pcColor       车牌颜色（"蓝色","黄色","白色","黑色",“绿色”）
                             *  @param  [OUT] pcPicData     抓拍图片数据
                             *  @param  [OUT] u32PicSize    抓拍图片缓冲区大小
                             *  @param  [OUT] pu32PicLen    抓拍图片实际长度
                             *  @return 1表示成功，0表示失败
                             */
                            success = ipcsdk.ICE_IPCSDK_Trigger(intPtr, strNum, strColor, pdata, 1048576, ref len);//软触发
                            if (success == 1 && len > 0)
                            {
                                Value = strNum.ToString();
                                ValueChanged?.Invoke(Value);
                                Message = $"车牌识别正常 | 时间：{DateTime.Now.ToLongTimeString()},{Value},{strColor.ToString()}";
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                Message = ex.Message;

            }
            
        }
    }
}
